package eai.tp2.lpco.requests;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import eai.tp2.lpco.database.DigitalCamera;
import eai.tp2.lpco.database.Order;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.database.Order.Status;


/**
 * 
 */
@Stateless
public class RequestBean implements IRequest {

	@PersistenceContext(unitName = "myLpcoCatalogue")
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public RequestBean() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public DigitalCamera getCamera(String name) {

		Query q = em
				.createQuery("select c from DigitalCamera c where modelName = '"
						+ name + "'");
		System.out.println("olha a query");
		
		if (q.getResultList().size() >= 1)
			return (DigitalCamera) q.getSingleResult();
		
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getCameraNames() {

		List<String> cameraNames = em.createQuery(
				"select modelName from DigitalCamera").getResultList();

		return cameraNames;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getModelNames(String brand) {

		List<String> cameraNames = em.createQuery(
				"select modelName from DigitalCamera where brandName = '"
						+ brand + "'").getResultList();

		return cameraNames;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> getUserHistory(String username) {
		List<Order> orders = em.createQuery("select o from Order o where username = '" + username+"'").getResultList();		
		return orders;
	}

	public Order getOrder(Integer orderId) {

		Query q = em.createQuery("select o from Order o where orderId = "
				+ orderId);
		if (q.getResultList().size() >= 1)
			return (Order) q.getSingleResult();
		return null;
	}

	@Override
	public User getPersonalInfo(String username) {
		User user = null;
		if ((user = em.find(User.class, username)) != null)
			return user;
		return null;
	}

}
